#   Copyright 2006 Jerome Lacoste (jerome@coffeebreaks.org)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
class Worklog < ActiveRecord::Base

  belongs_to :assignment
  validates_presence_of :duration, :done_at, :description, :assignment_id
  validates_numericality_of :duration

  def project
    self.assignment.project
  end

  def worker
    self.assignment.user
  end


  protected 
  def validate
    errors.add(:duration, "should be positive") unless duration.nil? || duration >= 0.0
    # FIXME validates hook ?
#    errors.add(:description, "should not empty") unless description.nil? || description.length > 0
  end

  def self.find_by_worklog_search_criteria(search_criteria)
    Worklog.find_by_sql( [ "select w.* from worklogs as w, assignments as a, projects as p, clients as c" +
                           " where w.assignment_id = a.id" +
                           " and a.project_id = p.id" +
                           " and p.client_id = c.id" + 
                           " and c.id = ?"+
                           " and ( ? IS NULL || w.done_at > ?) " +
                           " and ( ? IS NULL || w.done_at < ?) " + 
                           "order by w.done_at", 
                         search_criteria.client_id, search_criteria.from_date, search_criteria.from_date,
# note: time part is not propagated from the UI (so we assume the day is inclusive)
                         search_criteria.to_date, search_criteria.to_date + 24.hours ] )
  end

end
